package communication;

import java.io.IOException;
import java.net.Socket;
import org.ftp4che.io.BandwidthControlledInputStream;
import org.ftp4che.io.BandwidthControlledOutputStream;

public class ServerSecureConnectionControlled extends ServerSecureConnection {


	private static final int  KBits = 128; 

	protected BandwidthControlledOutputStream sendControlled;
	protected BandwidthControlledInputStream receiveControlled;


	public ServerSecureConnectionControlled(Socket socket, int bandwidth)
	throws ConnectionException{

		super(socket);

		receiveControlled = new BandwidthControlledInputStream(receive,bandwidth*KBits);
		sendControlled= new BandwidthControlledOutputStream(send,bandwidth*KBits);
	}


	protected void doSend(byte[] buffer)
	throws ConnectionException {
		try {
			sendControlled.write(buffer);
			send.flush();
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}
	}


	protected void doSend(byte[] buffer, int init, int length)
	throws ConnectionException {
		try {
			sendControlled.write(buffer,init,length);
			send.flush();
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}		
	}


	protected int doReceiveBytes(byte [] buffer)
	throws ConnectionException{
		try {
			return (int) receiveControlled.read(buffer);
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}
	}


	protected void doClose()
	throws ConnectionException{

		try {
			if(socket!=null){
				socket.close();
				socket = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(send!=null){
				send.close();
				send = null;
			}
		}catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(receive!=null){
				receive.close();
				receive = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(sendControlled!=null){
				sendControlled.close();
				sendControlled = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(receiveControlled!=null){
				receiveControlled.close();
				receiveControlled = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}		
	}


}
